<?php
error_reporting(0);
session_start();


define("DATABASE_NAME", "advmanagement");
define("DATABASE_USER", "root");
define("DATABASE_PASSWORD", "");
define("DATABASE_HOST", "localhost");
define("SITE_NAME", "Example");

/*
define("DATABASE_NAME", "b2bsupplierdb");
define("DATABASE_USER", "vnsupplierscom");
define("DATABASE_PASSWORD", "abc123");
define("DATABASE_HOST", "vnsupplierscom.fatcowmysql.com");
define("SITE_NAME", "VNSuppliers");
*/
define("NULL_VAL", "(NULL)");
 
$requestURI = $_SERVER["REQUEST_URI"];

$uris = explode("/", $requestURI);
//print_r($uris);
if ($uris[1]!="admin" && count($uris)>=3) {
	define("URL_SITE", "http://".$_SERVER["HTTP_HOST"]."/".$uris[1]."/");
	$root = $_SERVER["DOCUMENT_ROOT"]."/".$uris[1]."/";
}
else {
	define("URL_SITE", "http://".$_SERVER["HTTP_HOST"]."/");
	$root = $_SERVER["DOCUMENT_ROOT"]."/";
} 

define("WS_ROOT", "$root");
define("AD_NAME", "admin");
/*
$args = $_SERVER["argv"];
if (is_array($args) && count($args)>0) {
	for ($i=0; $i<count($args); $i++) {
		$varVals = explode("=", $args[$i]);
		${$varVals[0]} = $varVals[1];
	} 
}

//$vars = $HTTP_POST_VARS;
while (list($key, $val) = each($HTTP_POST_VARS)) {
    ${$key} = $val;
}
*/
if (ini_get("register_globals")==null || ini_get("register_globals")==0 || ini_get("register_globals")=="")
{
	foreach ($_GET as $k => $v ) {
		${$k} = $v;
	} 
	foreach ($_POST as $k => $v ) {
		${$k} = $v;
	}

}

define("CONTACT_EMAIL", "thesminh@yahoo.com");

$UserTypes = array("1"=>"Administrator", "2"=>"Normal");

if (strpos(strtoupper($HTTP_USER_AGENT), "FIREFOX")===false) 
	define("IE", "true");
else
	define("IE", "false");
	
define("ROWS_OF_USERLIST_ADMIN", "2");
define("ROWS_OF_ADMIN_LIST", "10");

function QueryString() {
	global $REDIRECT_QUERY_STRING, $HTTP_SERVER_VARS, $QUERY_STRING;
	$queryString = $REDIRECT_QUERY_STRING;
	if (!isset($queryString) || $queryString=="") $queryString = $HTTP_SERVER_VARS["REDIRECT_QUERY_STRING"];
	if (!isset($queryString) || $queryString=="") $queryString = $QUERY_STRING;
	return $queryString;
}

function InDir($dir, $path) {
	if (strpos(strtolower($path), strtolower($dir))===false) return false;
	return true;
}

function NewDB($dbHost, $dbName, $dbUser, $dbPass) {
	$db = new DB_Sql();
	$db->Database = "$dbName";
	$db->User     = "$dbUser";
	$db->Password = "$dbPass";
	$db->Host     = "$dbHost";

	return $db;
}

function IsIE() {
	return IE=="true";
}

function ToHTML($strValue)
{
  return htmlspecialchars($strValue);
}
// ----------------------------------------------------------------------------------------------
function ToURL($strValue)
{
  return urlencode($strValue);
}
// ----------------------------------------------------------------------------------------------
function GetParam($ParamName)
{
  global $_POST;
  global $_GET;

  $ParamValue = "";
  if(isset($_POST[$ParamName]))
    $ParamValue = $_POST[$ParamName];
  else if(isset($_GET[$ParamName]))
    $ParamValue = $_GET[$ParamName];

  return $ParamValue;
}
// ----------------------------------------------------------------------------------------------
function IsNumner($string_value)
{
  if(is_numeric($string_value) || !strlen($string_value))
    return true;
  else 
    return false;
}
//-------------------------------------------------------------------------------------------
function ToSQLPostVAL($value)
{
	if ($value==NULL_VAL) 
		return "NULL";
   // Stripslashes
   if (get_magic_quotes_gpc()) {
	   $value = stripslashes($value);
   }
   // Quote if not a number or a numeric string
   $value = "'" . mysql_escape_string($value) . "'";
   
   return $value;
}
function ToSQLNormalVAL($value)
{
     return  "'" . mysql_escape_string($value) . "'";
}
// ----------------------------------------------------------------------------------------------
function Strip($value)
{
  if(get_magic_quotes_gpc() == 0)
    return $value;
  else
    return stripslashes($value);
}
// ----------------------------------------------------------------------------------------------
function IsEmail($address) {
    if( ereg( ".*<(.+)>", $address, $regs ) ) {
        $address = $regs[1];
    }
    if(ereg( "^[^@  ]+@([a-zA-Z0-9\-]+\.)+([a-zA-Z0-9\-]{1,})\$",$address) )
        return true;
    else
        return false;
}
// ----------------------------------------------------------------------------------------------
function ChkNumber($strNumber) {
	$strNumber = trim($strNumber);
	if (strlen($strNumber) == 1 && !isNumber($strNumber)) return "not a number";
	if (substr($strNumber, 0, 1)=="-" || substr($strNumber, 0, 1)=="+") $strNumber = substr($strNumber, 1);
	$comma = 0;
	for ($i=0; $i<=strlen($strNumber); $i++) {
		$pt = substr($strNumber, $i, 1);
		if (!isNumber($pt) && $pt!=".") return "not a number";
		else if($pt==".") $comma++;
	}
	if ($comma>=2) return "not a number";
	return "";
}
// ----------------------------------------------------------------------------------------------------------
function CheckDateMMDDYY($strdate, $split) {
	$msgErr = "Invalid date! Enter the date in 'mm/dd/yyyy' format!";
	if((substr_count($strdate,$split))<>2){
		return $msgErr;
	}
	
	$pos = strpos($strdate,"/");
	$month = substr($strdate,0,($pos));
	$date= substr($strdate,($pos+1),($pos));
	$result=ereg("^[0-9]+$",$date,$trashed);
	if(!($result))
		return $msgErr;
	$year= substr($strdate,($pos+4),strlen($strdate));

	if(!checkdate($month, $date, $year)) {
		return $msgErr;
	}
	return "";
}

function CheckDateDDMMYY($strdate, $split) {
	$msgErr = "Invalid date! Enter the date in 'mm/dd/yyyy' format!";
	if((substr_count($strdate,$split))<>2){
		return $msgErr;
	}
	
	$pos = strpos($strdate,"/");
	$month = substr($strdate,0,($pos));
	$date= substr($strdate,($pos+1),($pos));
	$result=ereg("^[0-9]+$",$date,$trashed);
	if(!($result))
		return $msgErr;
	$year= substr($strdate,($pos+4),strlen($strdate));

	if(!checkdate($month, $date, $year)) {
		return $msgErr;
	}
	return "";
}

function GetIDSeed() {
	global $UserID;
	return $UserID."-".implode("", gettimeofday());
	//return "";
}

function GetDirName() {
	return implode("", gettimeofday());
}
function CreateDir($dir) {
	while (!is_dir($dir)) {
		   mkdir($dir,0777);
	}
	return $dir;
}
function AutoCreateDir($dir)
{
	for ($i=1; $i<999; $i++) 
	{
		$createDir = $dir."/".sprintf("%03d", $i);
		if (!is_dir($createDir)) {
			   //mkdir($createDir,0777);
				$createDir = sprintf("%03d", $i);
			   break;
		}
		
	}
	return $createDir;
}
function FormatNumeric($value, $isDecimal) {
	$retValue = "";
	if ($isDecimal) {
		$retValue = sprintf("%01.2f", $value);
	} else {
		$retValue = sprintf("%d", $value);
	}
	$thapphan = substr($retValue, strlen($retValue)-3);
	$nguyen	  = substr($retValue, 0, strlen($retValue)-3);
	$du = strlen($nguyen)%3;
	if ($du!=0)
		$nguyen = str_repeat("0", 3-$du).$nguyen;
	if (strlen($nguyen)>3)
		$nguyen = wordwrap($nguyen, 3, ",", 1);
	if ($du!=0)
		$nguyen = substr($nguyen, 3-$du);
	//echo "<!-- ||$nguyen$thapphan || -->";
	//exit;
	$retValue = str_replace(",.", ".", $nguyen.$thapphan);
	return $retValue;
	
}
function FormatDateSQL($value) {
	$date = explode("/", $value);
	if ($value=="" || count($date)<3) return "0000-00-00 00:00:00";
	$retValue = sprintf("%04d", $date[2])."-".sprintf("%02d", $date[1])."-".sprintf("%02d", $date[0])." 00:00:00";
	return $retValue;
}
function DateDDMMYYY($value, $sep="/") {
	if ($value!="") {
		$retValue = substr($value, 8, 2).$sep.substr($value, 5, 2).$sep.substr($value, 0, 4);
		if ($retValue!="00$sep00$sep0000")
			return $retValue;
	}
	return "";
}
function DateMMDDYYY($value, $sep="/") {
	if ($value!="") {
		$retValue = substr($value, 5, 2).$sep.substr($value, 8, 2).$sep.substr($value, 0, 4);
		if ($retValue!="00$sep00$sep0000")
			return $retValue;
	}
	return "";
}
function VNSupplierShowDate($value, $hastime=false)
{
	$months = array("01"=>"Jan", "02"=>"Feb", "03"=>"Mar", "04"=>"Apr", "05"=>"May", "06"=>"Jun", 
						"07"=>"Jul", "08"=>"Aug", "09"=>"Sep", "10"=>"Oct", "11"=>"Now", "12"=>"Dec");
	if ($value!="" && $value!="0000-00-00 00:00:00") {
		$day = substr($value, 8, 2);
		$month = substr($value, 5, 2);
		$year = substr($value, 0, 4);
		$time = substr($value, 10);
		
		return $day."-".$months[$month]."-".$year.($hastime?$time:"");
	}
	return "";
}
function VNSupplierDateToMysql($value)
{
	if ($value== "00-00-0000 00:00:00" || $value== "")
			$value = "0000-00-00 00:00:00";
		else	
			$value	=   date( 'Y-m-d H:i:s', strtotime($value));
	return $value;
}
function GetStartNameofPic($dir, &$startName, $len) {
	if (is_dir($dir)) {
	   if ($dh = opendir($dir)) {
	   	   $lastName = "000.gif";
		   while (($file = readdir($dh)) !== false) {
			   if ($file != "." && $file != "..") {
			   		$lastName = $file;
			   }
		   }
		   $startName = substr($lastName, 0, $len);
		   $start = (int)$startName+1;
		   $startName = sprintf("%03d", $start);
		   //echo $startName;
		   closedir($dh);
	   }
	}
}
function GetUploadFileName($dir, $startName) {
	$arrayFiles = array();
	if (is_dir($dir)) {
	   if ($dh = opendir($dir)) {
			   while (($file = readdir($dh)) !== false) {
				   if ($file != "." && $file != "..") 
						$arrayFiles[count($arrayFiles)] = $file;
			   }
		 }
		 closedir($dh);
	}
	//print_r($arrayFiles);
	$validName = "";
	$exist = false;
	for ($i=65; $i<=90 && !$exist; $i++) {
		$validName = $startName.chr($i);
		$exist = false;
		for ($j=0; $j<count($arrayFiles) && !$exist; $j++) {
			//echo "<br>".$arrayFiles[$j]."-".$validName."<br>";
			if (strpos($arrayFiles[$j], $validName)===false) 
				$exist = false; // not found
			else $exist = true; // found
		}
		if ($exist) $exist = false; // Continue with next value
		else break;
	}
	return $validName;
}

function UploadFile($filename, $uploadPath)
{
	/*
	$fname = "";
	if (isset($file_name) && $file_name != "") {
		$dir = CreateDir($uploadPath);
		$fname = $file_name;
		while (file_exists("$dir/".$fname)) 
			$fname = rand(100, 999).$file_name;

		move_uploaded_file($file, "$dir/".$fname);
	}
	*/
	if (isset($_FILES[$filename]))
	{
		$file = $_FILES[$filename]["tmp_name"];
		if (isset($file) && $file!=null && $file!="")
		{
			$file_name = $_FILES[$filename]["name"];
			$dir = CreateDir($uploadPath);
			$fname = $file_name;
			while (file_exists("$dir/".$fname)) 
				$fname = rand(100, 999).$file_name;
	
			move_uploaded_file($file, "$dir/".$fname);
		}
	}
	return $fname;
}

function ShowObject($obj, $comment="") {
	echo "$comment:<pre>";
	print_r($obj);
	echo "</pre>";
}

function RowCount($db, $tableName, $whereStr, &$errorMsg, $joinTables="", $onFields="") {
	$errorMsg = "";	
	$rowCount = 0;
	$joinClause = "";
	for ($i=0; is_array($joinTables) && $i<count($joinTables); $i++)
	{
		$joinClause .= " LEFT JOIN ".$joinTables[$i]." ".$joinTables[$i]." ON ".$onFields[$i];
	}
	$query	= "SELECT COUNT('x') AS RowCount FROM $tableName $joinClause";		
	if ($whereStr!="") $query = $query." WHERE ".$whereStr;

	if (!$db->query($query)) 		
		$errorMsg	= mysql_error()." Query: $query.";		
	else if ($db->next_record()) 
			$rowCount = $db->f("RowCount");
		
	return $rowCount;
}

function GetComboBox($db, $tableName, $whereStr, $orderByStr, $optName, $fieldValue, $fieldText, $firstText, $firstValue, &$defaultVAL, $extraAttr, $moreAtt) {	
	$errorMsg = $returnData = "";	
	$query	= "SELECT * FROM $tableName";		
	
	if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) {
		$defaultVAL = $firstValue;
		$returnData .= "\t<OPTION VALUE='$firstValue' SELECTED>$firstText</OPTION>\r";		
	} else $returnData .= "\t<OPTION VALUE='$firstValue'>$firstText</OPTION>\r";		

	if ($whereStr!="") $query = $query." WHERE ".$whereStr;
	if ($orderByStr!="") $query = $query." ORDER BY ".$orderByStr;
	if ($limit!="") $query = $query." LIMIT ".$limit;

	if (!$db->query($query)) {		
		$errorMsg	= mysql_error()." Query: $query.";		
	} else {		
		while ($db->next_record()) 	{
			$value		= $db->f($fieldValue);		
			$display	= $db->f($fieldText);			
			if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) $defaultVAL = $value;
			if ($value == $defaultVAL)				
				$returnData .= "\t<OPTION VALUE='$value' SELECTED>$display</OPTION>\r";			
			else				
				$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		}
	}	

	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr $moreAtt>\r$returnData</SELECT>\r";		
	
	return $returnData;	
}

function GetNewComboBox($db, $tableName, $whereStr, $orderByStr, $optName, $fieldValue, $fieldText, $firstText, $firstValue, &$defaultVAL, $extraAttr, $moreAtt) {	
	$errorMsg = $returnData = "";	
	$query	= "SELECT * FROM $tableName";		
	
	if($firstText !== "") {
		$returnData .= "\t<OPTION VALUE='$firstValue' SELECTED>$firstText</OPTION>\r";	
	}

	if ($whereStr!="") $query = $query." WHERE ".$whereStr;
	if ($orderByStr!="") $query = $query." ORDER BY ".$orderByStr;
	if ($limit!="") $query = $query." LIMIT ".$limit;

	if (!$db->query($query)) {		
		$errorMsg	= mysql_error()." Query: $query.";		
	} else {		
		while ($db->next_record()) 	{
			$value		= $db->f($fieldValue);		
			$display	= $db->f($fieldText);						
			$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		}
	}	

	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr $moreAtt>\r$returnData</SELECT>\r";		
	
	return $returnData;	
}


function GetComboBoxFromVars($arrValues, $optName, $firstText, $firstValue, &$defaultVAL, $extraAttr) {
	$returnData = "";	
	
	if ($firstValue!="")			
		$returnData .= "\t<OPTION VALUE='$firstValue'>$firstText</OPTION>\r";	
	$i = 0 ;
	while (list($value, $display) = each($arrValues)) 	{
		if ((!isset($defaultVAL) || $defaultVAL=="") && $i==0) $defaultVAL = $value;
		if ($value == $defaultVAL)				
			$returnData .= "\t<OPTION VALUE='$value' SELECTED>$display</OPTION>\r";			
		else				
			$returnData .= "\t<OPTION VALUE='$value'>$display</OPTION>\r";		
		$i++;
	}
	if ($returnData!="") $returnData = "\r<SELECT NAME='$optName' $extraAttr>\r$returnData</SELECT>\r";		
	return $returnData;
}

function Paging($page, $rowCount, $rowsOfPage, $nextText, $prevText, $btnGoText, $linkCls, $textCls, $inputCls, &$note, $formName) {	
	$btnGoToPage = $btnGoText;
	$btnNextPage = $nextText;
	$btnPrevPage = $prevText;	
	$returnData = "";	$notes	= "";	
	if ($rowCount>0) {		
		$pages = ceil($rowCount/$rowsOfPage);		
		if ($page>1)  			
			$prev = "<a href='javascript: _goPage($page, -1,".$formName.");' class='$linkCls' title='$btnGoToPage ".($page-1)."'>$btnPrevPage</a>"; 		
		else 			
			$prev = "<span class='$textCls'>$btnPrevPage</span>";		
		if ($page*$rowsOfPage < $rowCount) 			
			$next = "<a href='javascript: _goPage($page, 1,".$formName.");' class='$linkCls' title='$btnGoToPage ".($page+1)."'>$btnNextPage</a>"; 		
		else 			
			$next = "<span class='$textCls'>$btnNextPage<span>";		
		$returnData = "$prev <span class='$textCls'>|</span> $next&nbsp;&nbsp;&nbsp;";		
		$returnData .= "<a href=\"javascript: _go(".$formName.");\">$btnGoToPage</a>&nbsp;";		
		$returnData .="<input name=numGo type=text size=2 maxlength=3 class='$inputCls'>&nbsp;&nbsp;<span class='$textCls'> $page/$pages</span>";		
		$note = "<span class='$textCls'>".(($page-1)*$rowsOfPage+1)."-".($page*$rowsOfPage>$rowCount?$rowCount:$page*$rowsOfPage);	
	}	
	if (ceil($rowCount/$rowsOfPage)<2) return "";
	else return $returnData;
}

function PagingGroup($page, $rowCount, $rowsOfPage, $itemsOfGroup, $linkCls, $textCls, $inputCls, &$note, $formName) {	
	$pages =  ceil($rowCount/$rowsOfPage);	
	$numGroup = ceil($pages/$itemsOfGroup);	
	if ($page>$pages) $page = $pages;	
	$inGroup = ceil($page/$itemsOfGroup);	
	$returnData = "";	$notes	= "";	
	if ($rowCount>0) {		
		for ($i=($inGroup-1)*$itemsOfGroup+1; $i<=($inGroup-1)*$itemsOfGroup+$itemsOfGroup && $i<=$pages; $i++) {
			if ($i==$page)				
				$returnData .= "<span class='$textCls'><font color='red'>$i</font></span> ";			
			else				
				$returnData .= "<a href='javascript: _goPage($i-1, 1,".$formName.");' class='$linkCls' title='Go to page $i'><b>$i</b></a> ";		
		}		
		if ($returnData!="") {			
			if ($numGroup>1) {				
				if ($inGroup>1)					
					$returnData = "<b>[</b><a href=\"javascript: _goPage($page-$itemsOfGroup-1, 1,".$formName.");\" class='$linkCls' title='Jump to previous $itemsOfGroup pages'><b>Previous  $itemsOfGroup</b></a><span class='$textCls'><b>] </b></span>".$returnData;				
				else 					
					$returnData = "<span class='$textCls'> [Previous  $itemsOfGroup] </span><span class='$textCls'> </span>".$returnData;				
				if ($inGroup<$numGroup)					
					$returnData .= "<span class='$textCls'><b> [</b></span><a href=\"javascript: _goPage($page+$itemsOfGroup-1, 1,".$formName.");\" class='$linkCls' title='Jump next to $itemsOfGroup pages'><b>Next  $itemsOfGroup</b></a><b>] </b>";				
				else 					
					$returnData .= "<span class='$textCls'><b> </b></span><span class='$textCls'> [Next  $itemsOfGroup] </span>";			
			}			
			if ($page>1)				
				$returnData = " <b>[</b><a href=\"javascript: _goPage(0, 1,".$formName.");\" class='$linkCls' title='Go to page 1'><b>First</b></a><span class='$textCls'><b>] </b></span>".$returnData;			
			else 				
				$returnData = "<span class='$textCls'> [First] </span><span class='$textCls'><b>  </b></span>".$returnData;			
			if ($page<$pages)				
				$returnData .= " <b>[</b><a href=\"javascript: _goPage($pages-1, 1,".$formName.");\" class='$linkCls' title='Go to page $pages'><b>Last</b></a><span class='$textCls'><b>] </b></span>";			
			else 				
				$returnData .= "  <span class='$textCls'> [Last]</span><span class='$textCls'></span>";		
		}		
		$note = "<span class='$textCls'>Records from ".(($page-1)*$rowsOfPage+1)."-".($page*$rowsOfPage>$rowCount?$rowCount:$page*$rowsOfPage)." of $rowCount";	
	}	
	if (ceil($rowCount/$rowsOfPage)<2) return "";
	else return $returnData;
}

?>